var title;
var workbook;
var jsonexcel;
var maprule;

layui.use(['form'], function () {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.$;

    // let jsonexcel;
    var selectObj = document.getElementById("sheetNames");

    // 监听member-file变更，更新sheetNames下拉列表
    document.getElementById('import-file').addEventListener('change', function (e) {   //选择文件后执行
        // 清理下拉列表（sheetNames）
        $('#sheetNames option').remove();

        $('.import option').remove();

        var optEle1 = document.createElement("option");
        optEle1.setAttribute("value", "default");
        optEle1.appendChild(document.createTextNode("==选择sheetname=="));
        selectObj.appendChild(optEle1);

        let files = e.target.files;
        if (files.length == 0) return;
        let file = files[0];
        let reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = function (e) {   //处理load事件。读取操作完成时触发。
            let data = e.target.result;
            
            workbook = XLSX.read(data, { type: 'binary' }); //XLSX：/xlsx.core.min.js 通过XLSX.read(data, {type: type})方法读取excel 后面介绍

            let sheetNames = workbook.SheetNames; // 工作表名称集合
            for (i = 0; i < sheetNames.length; i++) {
                            
                // 填充sheetname下拉列表
                var optEle2 = document.createElement("option");
                optEle2.setAttribute("value", sheetNames[i]);
                optEle2.appendChild(document.createTextNode(sheetNames[i]));
                selectObj.appendChild(optEle2);
            }
            layui.form.render("select");
        };
    });

    var dealerSelect = document.getElementById("dealer_id");
    $.ajax({
        url: '/Dealer/list',
        type: "post",
        data: `{"page":1,"limit":15}`,
        datatype: "json",
        success: function (data) {
            // console.log("Debug data:", data);
            let optEle1 = document.createElement("option");
            // optEle1.setAttribute("value","default");
            dealerSelect.appendChild(optEle1);
            for (var x = 0; x < data.data.length; x++) {
                let optEle1 = document.createElement("option");
                optEle1.setAttribute("value", data.data[x].dealer_uid);
                optEle1.appendChild(document.createTextNode(data.data[x].dealer));
                dealerSelect.appendChild(optEle1);
            }
            layui.form.render("select");
        }
    });

    form.on('select(sheetNames)', function (data) {
        // console.log("debug select:",data.value);
        // 清理表单中checkbox
        $('.import option').remove();

        // var mappingMembers = document.getElementById("headcheck");
        const sheet2JSONOpts = { //解决单元格空时，对应数据会在数据集中提出的问题。
            defval:''
        }
        
        jsonexcel =  XLSX.utils.sheet_to_json(workbook.Sheets[data.value],sheet2JSONOpts);

        console.log("debug Sheets:",jsonexcel);

        //判断如果sheet页数据为空，则提示
        if (jsonexcel.length == 0) {
            alert("此页无数据，请选择其它sheet！");
        } 
        layui.form.render("");
    });

    form.on('select(dealer_id)', function (data) {
        // console.log("Debug Data:", data);
        let dealerid = data.value;
        $.ajax({
            url: '/MappingRules/view',
            type: "get",
            data: 'dealerid=' + dealerid,
            datatype: "json",
            success: (res) => {
                // console.log("Debug rules:", res);
                maprule = res;
                initable();
                layui.form.render("");
            }
        });
        //按照数据设置select 已选
        
    });

    form.on('submit(saveBtn)', function (data) { //监听提交
        // console.log("Debug data:", data);
        var confirm = layer.confirm("确定导入吗？", {
            title: '确认'
        }, function () {
            // console.log("Debug jsonexcel:", jsonexcel);

            for (let x = 0; x < jsonexcel.length; x++) { //清洗无效行数据
                if (Object.keys(jsonexcel[x]).length != Object.keys(jsonexcel[0]).length) {

                    console.log("Debug fixbug [x]:", Object.keys(jsonexcel[x]));
                    console.log("Debug fixbug:", Object.keys(jsonexcel[0]).length);


                    jsonexcel.splice(x, 1);

                    continue;
                }
            }
        
            // 获取数据对照表 [{dbkey:username,impkey:收件人}]
            let mapdata = getMaplist();
            // 依照mapdata修改jsonexcel中的键，重组成resdata
            let resdata = new Array(jsonexcel.length).fill({});
        
            for (let y = 0; y < mapdata.length; y++) {//4
                let a = mapdata[y].dbkey;
                let b = mapdata[y].impkey;
                let d = jsonexcel.map(function (item) {
                    return {
                        [a]: item[b]
                    }
                });
        
                for (let zz in d) {
                    if (Object.keys(d[zz]) == "userphone") {
                        // console.log("Debug A!!",x,selectPhoneNum(d[zz].userphone));
                        d[zz].userphone = selectPhoneNum(d[zz].userphone);
                    }
                    resdata[zz] = { ...resdata[zz], ...d[zz] };
                }
        
            }
            // console.log("Debug resdata:", resdata);
            let querydata = uniqueArr(resdata);
            for (let a in querydata) {
                querydata[a].dealer_id = data.field.dealer_id;
            }
            // console.log("Debug querydata:", querydata);
            var wait = layer.load();
            // return resdata;
            // 调用接口/Order/add，添加数据
            $.ajax({
                url: "/Order/add",
                type: "post",
                data: JSON.stringify(querydata),
                datatype: "json",
                success: (res) => {
                    layer.close(wait);
                    var index = layer.alert(JSON.stringify(res), {
                        title: '最终的提交信息'
                    }, function () {
        
                        // 关闭弹出层
                        layer.close(index);
        
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(iframeIndex);
                    });
                }
            })
            // 关闭弹出层
            layer.close(confirm);
        });

        return false;
    });

    window.getMaplist = function () {
        let res = [];

        var objselect = document.getElementsByClassName('import');
        
        for (x = 0; x < objselect.length; x++) {
            var dbkey = objselect[x].id;
            var impkey = $("#" + dbkey + " option:selected").val();
            if (impkey != "default") {
                let c = new Object();
                c.dbkey = dbkey;
                c.impkey = impkey;
                res.push(c);
            }
        }
        // console.log("Debug maplist:", res);
        return res;
    };

    window.uniqueArr = function (arr) {
        let result = []; //中间数组
        let tempJson = {}; //缓存对象
        for (var i = 0; i < arr.length; i++) {
            //如果在结果数组result中没有找到arr[i],则把arr[i]压入结果数组result中
    
            if (!tempJson[JSON.stringify(arr[i])]) {
                result.push(arr[i]);
                tempJson[JSON.stringify(arr[i])] = true;
            }
        }
        return result;
    };

    window.initable = function () { 
        $('.import option').remove();
        title = [
            { "id": "order_num", "view": "订单编号" },
            { "id": "goods", "view": "货品名称" },
            { "id": "goods_sku", "view": "规格名称" },
            { "id": "sum_goods", "view": "货品数量" },
            { "id": "mem_name", "view": "收货人" },
            { "id": "mem_phone", "view": "手机号" },
            { "id": "detailaddress", "view": "收货地址" },
            { "id": "offers", "view": "优惠" },
            { "id": "postage", "view": "邮费" },
            { "id": "remark", "view": "客服备注" },
            { "id": "remark1", "view": "客户备注" }
        ];
        // console.log("debug title:",title);
        var Obj = document.getElementById("mapping");
        for (var x = 0; x < title.length; x++) {
            var objselect = document.getElementById(title[x].id);

            var optEle = document.createElement("option");
            optEle.setAttribute("value", "default");
            optEle.appendChild(document.createTextNode("===选择列==="));
            objselect.appendChild(optEle);

            for (var y = 0; y < Object.keys(jsonexcel[0]).length; y++) {   //长度由sheet页内，列的数量决定
                var optEle1 = document.createElement("option");
                // 需要excel标题列名称
                optEle1.setAttribute("value", Object.keys(jsonexcel[0])[y]);
                optEle1.appendChild(document.createTextNode(Object.keys(jsonexcel[0])[y]));
               
                for (let z = 0; z < maprule.length;z++) { 
                    if (title[x].view === maprule[z].exp_head) { 
                        if (Object.keys(jsonexcel[0])[y] === maprule[z].imp_head) {
                            optEle1.setAttribute("selected", "selected");
                            // console.log("Debug double true:", title[x].view, Object.keys(jsonexcel[0])[y], maprule[z].imp_head);
                        }
                        // console.log("Debug title true:", title[x].view, Object.keys(jsonexcel[0])[y], maprule[z].imp_head);
                    }
                }
                objselect.appendChild(optEle1);
            }
        }
    };

});


function submit() {

}